<%@ Application Language="VB" %>

<script RunAt="server">

  Private _ApplicationPath As String = GetApplicationPath()
  
  Public Function GetApplicationPath() As String
    If HttpRuntime.AppDomainAppVirtualPath.Length > 1 Then
      Return HttpRuntime.AppDomainAppVirtualPath
    Else
      Return String.Empty
    End If
  End Function
  
  Private Function HandleTilde(ByVal url As String) As String
    If String.IsNullOrEmpty(url) Then
      Return url
    End If
    If url.StartsWith("^~/") Then
      Return "^" + _ApplicationPath + url.Substring("^~/".Length - 1)
    End If
    If url.StartsWith("~/") Then
      Return _ApplicationPath + url.Substring("~/".Length - 1)
    End If
    Return url
  End Function
  
  Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs on application startup
  End Sub
    
  Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    ' The following code performs URL rewriting for
    ' MyPageMethods.Products.FrmProduct.TestUrlFormat() and
    ' MyPageMethods.Products.FrmProduct.TestUrlFormatWithPost()

    Const PATTERN As String = "^~/SampleUrl/(.*)/(.*).aspx$"
    Const PATTERN_FOR_POST As String = "^~/SampleUrlWithPost/(.*).aspx$"

    Dim newUrl As String
    Dim regex As Regex
        
    ' Handle TestUrlFormat()
    regex = New Regex(HandleTilde(PATTERN))
    If regex.IsMatch(Request.RawUrl) Then
      newUrl = regex.Replace(Request.RawUrl, "~/Products/FrmProduct.aspx?" & MetaSapiens.PageMethods.PageMethodsEngine.PARAM_Method & "=$1&param=$2")
      newUrl = HandleTilde(newUrl)
    Else
      ' Handle TestUrlFormatWithPost()
      regex = New Regex(HandleTilde(PATTERN_FOR_POST))
      If regex.IsMatch(Request.RawUrl) Then
        newUrl = "~/Products/FrmProduct.aspx"
      Else
        ' Other method or URL
        newUrl = Request.RawUrl
      End If
    End If

    ' Handle HTTP POST
    newUrl = MetaSapiens.PageMethods.PageMethodsEngine.AddPostData(newUrl, Request)
    
    ' Update the path
    Context.RewritePath(newUrl, False)
  End Sub

  Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs on application shutdown
  End Sub
        
  Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when an unhandled error occurs
  End Sub

  Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when a new session is started
  End Sub

  Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when a session ends. 
    ' Note: The Session_End event is raised only when the sessionstate mode
    ' is set to InProc in the Web.config file. If session mode is set to StateServer 
    ' or SQLServer, the event is not raised.
  End Sub
       
</script>